import { create } from "zustand";
import { persist } from "zustand/middleware";

/**
 * 持久化用户状态
 */
export const useUserStore = create(
    persist(
        (set) => ({
            user: null,
            isLogin: false,
            _hasHydrated: false, // 标记hydration是否完成

            login: (userData) =>
                set((state) => ({
                    ...state,
                    user: userData,
                    isLogin: true,
                })),

            logout: () =>
                set({ user: null, isLogin: false }),

            setHasHydrated: (hasHydrated) => {
                set({
                    _hasHydrated: hasHydrated,
                });
            },
        }),
        {
            name: "user-storage",
            partialize: (state) => ({
                user: state.user,
                isLogin: state.isLogin,
                // 注意：不持久化_hasHydrated
            }),
            onRehydrateStorage: () => (state, error) => {
                if (error) {
                    console.error(" hydration 错误", error);
                } else {
                    // hydration完成后设置_hasHydrated为true
                    state.setHasHydrated(true);
                }
            },
        }
    )
);